package com.jokerpan.project.controller;

import com.jokerpan.project.annotation.AccessLimit;
import com.jokerpan.project.commons.ActionResult;
import com.jokerpan.project.commons.ListResult;
import com.jokerpan.project.commons.ResultBuilder;
import com.jokerpan.project.entity.Blogs;
import com.jokerpan.project.service.BlogsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("blogs")
@Api("博客空间Api")
@PreAuthorize("hasPermission('','user:list')")
public class BlogsController {

    @Resource
    BlogsService blogsService;

    @GetMapping("/queryList")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("查询所有博客")
    public ListResult<Object> queryList(Blogs blogs) {
        return ResultBuilder.buildListSuccess(this.blogsService.queryList(blogs));
    }

    @GetMapping("/queryByUserId")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("根据用户id查询博客")
    public ListResult<Object> queryByUserId(Blogs blogs) {
        return ResultBuilder.buildListSuccess(this.blogsService.queryByUserId(blogs));
    }

    @GetMapping("/queryById")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("根据主键id查询博客")
    public ListResult<Object> queryById(@RequestParam("id") Integer id) {
        return ResultBuilder.buildListSuccess(this.blogsService.queryById(id));
    }

    @PostMapping("/add")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("新增博客")
    @PreAuthorize("hasPermission('','user:add')")
    public ListResult<Object> add(@RequestBody Blogs blogs){
        Blogs blogs1 = this.blogsService.add(blogs);
        if (blogs1 != null){
            return ResultBuilder.buildListSuccess(blogs1);
        }else {
            return ResultBuilder.buildListFail("新增失败！");
        }
    }

    @PostMapping("/update")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("修改博客")
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult update(@RequestBody Blogs blogs) throws Exception {
        return this.blogsService.update(blogs);
    }

    @GetMapping("/delete")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("删除博客")
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult delete(@RequestParam("id") Integer id){
        return this.blogsService.deleteById(id);
    }

}
